<template>
  <a-modal
    width="65%"
    :title="title"
    :visible="visible"
    :positionCode="positionCode"
    @cancel="handleCancel"
    @ok="handleOk"
    :confirmLoading="confirmLoading"
  >
    <div style="display: flex;width: 100%;">
      <div style="flex:1;border-right: 1px solid #F1F1F1;width:100px;height: 100%">
        <div ref="search">
          <a-row :gutter="24">
            <span v-for="(item,index) in searchConfig" :key="index">
              <a-col :span="7">
                <a-input style="width: 140px;margin: 10px 0 0 10px;" v-if="item.type=='input'"
                         :type="item.inputType||'text'" :placeholder="item.placeholder||''"
                         @keyup.enter.native="search"
                         v-model="queryParam[item.name]"/>
                <a-select style="width: 140px;margin: 10px 0 0 10px;" v-if="item.type=='select'"
                          @keyup.enter.native="search"
                          v-model="queryParam[item.name]"
                          :placeholder="item.placeholder">
                  <a-select-option v-for="(v,i) in item.options" :key="i" :value="v.value">
                    {{ v.name }}
                  </a-select-option>
                </a-select>
              </a-col>
            </span>
            <a-col :span="7" ref="buttons" style="display: flex;margin-top: 10px;margin-left: 10px">
              <a-button type="primary" @click="search" icon="search" style="margin-bottom: 10px">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-bottom: 10px">重置</a-button>
            </a-col>
          </a-row>
        </div>
        <a-table
          ref="table"
          size="middle"
          class="Table"
          bordered
          :rowKey="keyVal"
          :scroll="{x:400,y:tableHeight }"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :customRow="onClickRow"
          :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: onSelectChange,onSelectAll:onSelectAll}"
          @change="handleTableChange">
        <span slot="delete" slot-scope="text, record">
           <a style="color: red;" @click="handleEdit(record)">删除</a>
        </span>
        </a-table>
      </div>
      <div style="flex:0.8;padding: 0px 20px 20px 20px;">
        <h2>已选列表</h2>
        <a-table
          ref="table"
          size="middle"
          class="Table"
          bordered
          :rowKey="keyVal"
          :columns="columns2"
          :dataSource="dataSource2"
          :pagination="ipagination2"
          :scroll="{x:400,y:365 }"
          @change="handleTableChange2">
        <span slot="delete" slot-scope="text, record">
           <a style="color: red;" @click="handleDelete(record)">删除</a>
        </span>
        </a-table>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { getAction, downFile, postAction } from '@api/manage'
import { filterObj } from '@/utils/util'

export default {
  name: 'myShuttleModal',
  data() {
    return {
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      visible: false,
      /* 数据源 */
      dataSource: [
        //   { productId: '10000', productName: '锅巴', id: 1 }, {
        //   productId: '20000',
        //   productName: '嘟嘟可',
        //   id: 2
        // }, { productId: '30000', productName: '伯爵', id: 3 }, {
        //   productId: '40000',
        //   productName: '牛牛',
        //   id: 4
        // }, { productId: '50000', productName: '蹦蹦', id: 5 }, {
        //   productId: '60000',
        //   productName: '哒哒哒',
        //   id: 6
        // }, { productId: '70000', productName: '啦啦啦', id: 7 }, { productId: '80000', productName: '开溜', id: 8 }
      ],
      dataSource2: [],
      heightTime: {},
      selectedRowKeys: [],
      selectionRows: [],
      lastIndex: [],
      selectedRowKeys2: [],
      selectionRows2: [],
      loading: false,
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      queryParam: {},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination2: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
    }
  },
  computed: {
    tableHeight() {
      let length = this.searchConfig.length
      if (length < 3 && length > 0) {
        return 300
      } else if (length < 5 && length > 2) {
        return 260
      } else if (length < 7 && length > 4) {
        return 220
      } else if (length >= 7) {
        return 160
      } else {
        return 350
      }

    }
  },
  props: {
    title: {//穿梭列表名称
      type: String,
      default: '穿梭列表'
    },
    clientType: {
      type: Number,
    },
    visitPosCode: {
      type: String
    },
    visitDate: {
      type: String
    },
    selectConfig: {
      type: Array,
      default: []
    },
    columns: {//左表行
      type: Array,
      default: []
    },
    keyVal: {
      type: String,
      default: 'id'
    },
    columns2: {//右表行
      type: Array,
      default: []
    },
    leftUrl: {//左表接口地址
      type: String,
      default: ''
    },
    positionCode: {//职位列表
      type: String,
      default: ''
    },
    searchConfig: {//左表查询条件
      type: Array,
      default: []
    }

  },
  // computed: {
  //   rightColumn: {}
  // },
  created() {
    // this.loadData()
    // console.log(this.keyVal)
  },
  mounted() {

  },
  // watch: {
  //   selectionRows: {
  //     deep: true,
  //     handler(val) {
  //       this.selectedRowKeys = val.map(item => item[this.keyVal])
  //       this.dataSource2 =JSON.parse(JSON.stringify(val))
  //     }
  //   }
  // },
  methods: {
    search() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.loadData(1)
    },
    searchReset() {
      var that = this
      for (var a in that.queryParam) {
        that.queryParam[a] = ''
      }
      that.loadData()
    },
    handleCancel() {
      this.queryParam = {}
      // this.heightTime.
      this.visible = false
      this.dataSource2 = []
      this.confirmLoading = false
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    close() {
      this.handleCancel()
    },
    onSelectAll(selected, selectedRows, changeRows) {
      let keys = this.selectedRowKeys
      if (selected) {
        //todo 选中
        changeRows.forEach(item => {
          let index = keys.findIndex(v => v == item[this.keyVal])
          if (index == -1) {
            this.selectedRowKeys.push(item[this.keyVal])
            this.selectionRows.push(item)
            this.dataSource2.push(item)
          }
        })
        console.log(this.selectedRowKeys, this.selectionRows, this.dataSource2)
      } else {
        //todo 取消选中
        changeRows.map(row => {
          let index = keys.findIndex(v => v == row[this.keyVal])
          if (index != -1) {
            this.selectedRowKeys.splice(index, 1)
            this.selectionRows.splice(index, 1)
            this.dataSource2.splice(index, 1)
          }
        })
      }
    },
    onSelectChange(selectedRowKeys, selectionRows, e) {
      let keys = this.selectedRowKeys
      let noSelectList = this.dataSource.filter(item=>{
        let _item = selectedRowKeys.find(v=>v==item[this.keyVal])
        return !_item
      })
      selectionRows.map(item => {
        let index = keys.findIndex(v => v == item[this.keyVal])
        if (index == -1) {
          this.selectedRowKeys.push(item[this.keyVal])
          this.selectionRows.push(item)
          this.dataSource2.push(item)
        }
      })
      noSelectList.map(item => {
        let index = keys.findIndex(v => v == item[this.keyVal])
        if (index != -1) {
          this.selectedRowKeys.splice(index,1)
          this.selectionRows.splice(index,1)
          this.dataSource2.splice(index,1)
        }
      })
    },

    handleSelect() {
      this.searchConfig.forEach((item, index) => {
        if (item.isRequest) {
          item.options = this.getSelecrVal(item)
        }
      })
    },
    getSelecrVal(item) {
      let options = []
      if (!item.url) {
        // this.$message.error("请设置url.list属性!")
        return
      }

      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(item.url))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      request(item.url).then((res) => {

        if (res.success) {
          let {
            records = [],
            total
          } = res.result
          if (res.result instanceof Array) {
            records = res.result
          }
          console.log(records)
          records.forEach((item2, index) => {
            options.push({ name: item2[item.valName], value: item2[item.keyName] })
          })
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        // debugger
        that.loading = false

      })
      return options

    },
    handleDelete(e) {
      let key = this.dataSource2.map(item => {
        return item[this.keyVal]
      })
      this.dataSource2.splice(key.indexOf(e[this.keyVal]), 1)
      this.selectionRows.splice(key.indexOf(e[this.keyVal]), 1)
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      // if (this.ipagination.current !== pagination.current) {
      //   this.selectionRows = []
      //   this.selectedRowKeys = []
      // }
      this.ipagination = pagination
      this.loadData()
    },
    handleTableChange2(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter2.column = sorter.field
        this.isorter2.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination2 = pagination
      this.loadData2()
    },
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows

    },
    onClickRow(record) {
      return {
        style:{
          'cursor': 'pointer'
        },
        on: {
          click: () => {
            const keys = this.selectedRowKeys
            let index = keys.findIndex(v => v == record[this.keyVal])
            if (index == -1) {
              this.selectedRowKeys.push(record[this.keyVal])
              this.selectionRows.push(record)
              this.dataSource2.push(record)
            } else {
              this.selectedRowKeys.splice(index, 1)
              this.selectionRows.splice(index, 1)
              this.dataSource2.splice(index, 1)
            }
          }
        }
      }
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}

      var param = Object.assign(sqp, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize

      return filterObj(param)
    },
    handleOk() {
      this.$emit('chooseOk', this.dataSource2)
      this.close()
    },
    loadData(arg) {
      if (!this.leftUrl || !this.leftUrl) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件
      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.leftUrl))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      params.positionCode = this.positionCode
      params.clientType = this.clientType
      params.visitPosCode = this.visitPosCode
      params.visitDate = this.visitDate
      params.lat = 0
      params.lng = 0
      console.log(this.positionCode)
      return request(this.leftUrl, params).then((res) => {
        if (res.success) {
          let {
            records = [],
            total
          } = res.result
          if (res.result instanceof Array) {
            records = res.result
          }
          that.dataSource = isNoPagnation ? res.result : records
          this.ipagination.total = res.result.total
          if (!isNoPagnation) that.ipagination.total = total || 0
          for (let i = 0; i < this.dataSource.length; i++) {
            this.dataSource[i].firstDate = ''
            this.dataSource[i].visitOrder = ''
            this.dataSource[i].visitFrequency = ''
          }
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        // debugger
        that.loading = false
      })
      // }
    }
  }
}
</script>

<style scoped>

</style>